import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import {AppConfig} from '../config';
import {TurboperHistory} from '../entity/turboper-history.model';
import {TurboperCurrent} from '../entity/turboper-current.model';
import {DatePipe} from '@angular/common';
import {Completd} from '../module/data-analysis/company-overhaul/company-overhaul.component';
import {InterceptorService} from './interceptor/interceptor-service';

@Injectable()
export class TurboperHistoryService {
  private fomat: string = 'yyyy-MM-dd HH:mm:ss';
  private param = 'operHistorys';

  private get url(): string {
    //return `http://192.168.15.3:8585/webapi/v1/${this.param}`
    return `${AppConfig.APP_RESTFUL}/${this.param}`;
  }

  private paramPer = 'performance/StopPowerLoss';

  private get urlPer(): string {
    return `${AppConfig.APP_RESTFUL}/${this.paramPer}`;
  }

  private headers = new Headers({
    'Content-Type': 'application/json'
  });

  constructor(private http: InterceptorService,
              private datePipe: DatePipe) {
  };

  getOperHistorysList(): Promise<TurboperHistory[]> {
    return this.http.get(this.url)
      .toPromise()
      .then(response => response.data as TurboperHistory[])
      .catch(this.handleError);
  }

  getOperHistorysByLimitNum(deviceId: number, limitNum: number): Promise<TurboperHistory[]> {
    //let url = `http://192.168.15.150:8585/webapi/v1/operHistorys`

    return this.http.get(`${this.url}/deviceId/${deviceId}/limitNum/${limitNum}`)
      .toPromise()
      .then(response => response.data as TurboperHistory[])
      .catch(this.handleError);
  }

  getOperHistorysByTurbineId(deviceId: number): Promise<TurboperHistory[]> {
    // let url = `http://192.168.15.150:8585/webapi/v1/operHistorys`
    return this.http.get(`${this.url}/turbineSubHisState/${deviceId}`)
      .toPromise()
      .then(response => response.data as TurboperHistory[])
      .catch(this.handleError);
  }

  update(turboperHistory: TurboperHistory): Promise<TurboperHistory> {


    //const url = `${this.url}`;
    return this.http.put(this.url, JSON.stringify(turboperHistory))
      .toPromise()
      .then(() => turboperHistory)
      .catch(this.handleError);
  }

  delete(id: number): Promise<void> {
    const url = `${this.url}/${id}`;
    return this.http.delete(url)
      .toPromise()
      .then(() => null)
      .catch(this.handleError);

  }

  getCurrentOperInfo(deviceId: number, operId: number): Promise<TurboperHistory> {
    //let url = `http://192.168.15.150:8585/webapi/v1/operHistorys`;
    return this.http.get(`${this.url}/currentOperInfo/deviceId/${deviceId}/operId/${operId}`)
      .toPromise()
      .then(response => response.data as TurboperHistory[])
      .catch(this.handleError);
  }

  getLossPower(deviceId: number, startTime: Date, endTime: Date) {
    let start = this.datePipe.transform(new Date(startTime), this.fomat);
    let end = this.datePipe.transform(new Date(endTime), this.fomat)
    return this.http.get(`${this.url}/deviceId/${deviceId}/startTime/${start}/endTime/${end}`)
      .toPromise()
      .then(response => {
          try {
            let result = response;
            switch (result.code) {
              case '200':
                return result.data;
              case '-1':
                throw new Error(result.message);
            }
          }
          catch (error) {
            this.handleError(error);
          }
          response.data
        }
      )
      .catch(this.handleError);
  }

  getLossPowerPer(deviceId: number, startTime: Date, endTime: Date) {
    let start = this.datePipe.transform(new Date(startTime), this.fomat);
    let end = this.datePipe.transform(new Date(endTime), this.fomat)
    return this.http.get(`${this.urlPer}/deviceId/${deviceId}/startTime/${start}/endTime/${end}`)
      .toPromise()
      .then(response => {
          try {
            let result = response;
            switch (result.code) {
              case '200':
                return result.data;
              case '-1':
                throw new Error(result.message);
            }
          }
          catch (error) {
            this.handleError(error);
          }
          response.data
        }
      )
      .catch(this.handleError);
  }

  removeTurboperCurrent(turboperCurrent: TurboperCurrent, lossPower: number) {
    //let url = `http://192.168.15.150:8585/webapi/v1/operHistorys/`
    return this.http.post(`${this.url}/removeOperation/lossPower/${lossPower}`, JSON.stringify(turboperCurrent))
      .toPromise()
      .then(res => {
        try {
          let result = res;
          switch (result.code) {
            case '200':
              return result.data;
            case '-1':
              throw new Error(result.message);
          }
        }
        catch (error) {
          this.handleError(error);
        }
      })
  }

  getTurboperHistByTurbines(deviceIds: number[], startTime: Date, endTime: Date, unPlantStop: string) {
    //let url = `http://192.168.15.150:8585/webapi/v1/operHistorys`
    let start = this.datePipe.transform(new Date(startTime), this.fomat);
    let end = this.datePipe.transform(new Date(endTime), this.fomat);
    let obj = {
      deviceIds: deviceIds,
      startTime: start,
      endTime: end,
      unPlantStop: unPlantStop
    }
    return this.http.post(`${this.url}/getBasicTurOperHistoryByOperHisVO`, JSON.stringify(obj))
      .toPromise()
      .then(res => {
        try {
          let result = res;
          switch (result.code) {
            case '200':
              return result.data;
            case '-1':
              throw new Error(result.message);
          }
        }
        catch (error) {
          this.handleError(error);
        }
      })
  }

  getTurboperHistByStartTime(startTime: Date, unPlantStop: string): Promise<Completd> {
    //let url = `http://192.168.15.150:8585/webapi/v1/operHistorys`
    let start = this.datePipe.transform(new Date(startTime), this.fomat);
    let obj = {
      startTime: start,
      unPlantStop: unPlantStop
    }
    return this.http.post(`${this.url}/getBasicTurOperHistoryByTime`, JSON.stringify(obj))
      .toPromise()
      .then(res => {
        try {
          let result = res;
          switch (result.code) {
            case '200':
              return result.data as Completd;
            case '-1':
              throw new Error(result.message);
          }
        }
        catch (error) {
          this.handleError(error);
        }
      })
  }

  getTurboperHistByType() {

    return this.http.get(`${this.url}/getBasicTurOperHistoryByType`)
      .toPromise()
      .then(response => response.data as TurboperHistory[])
      .catch(this.handleError);
  }

  getTurboperHistByTimeAndType(startTime: Date, endTime: Date, unPlantStop: string) {
    //let url = `http://192.168.15.150:8585/webapi/v1/operHistorys`
    let start = this.datePipe.transform(new Date(startTime), this.fomat);
    let end = this.datePipe.transform(new Date(endTime), this.fomat);
    let obj = {
      startTime: start,
      endTime: end,
      unPlantStop: unPlantStop
    }
    return this.http.post(`${this.url}/getBasicTurOperHistoryByTimeAndType`, JSON.stringify(obj))
      .toPromise()
      .then(res => {
        try {
          let result = res;
          switch (result.code) {
            case '200':
              return result.data;
            case '-1':
              throw new Error(result.message);
          }
        }
        catch (error) {
          this.handleError(error);
        }
      })
  }

  getHisOperListByTimeAndId(startTime: Date, endTime: Date, deviceIds: number[], operCategoryIds: number[]) {
    const start = this.datePipe.transform(new Date(startTime), this.fomat),
      end = this.datePipe.transform(new Date(endTime), this.fomat),
      url = `${this.url}/getHisOperList`,
      obj = {
        startTime: start,
        endTime: end,
        deviceIds: deviceIds,
        operCategoryIds: operCategoryIds
      };
    return this.http.post(url, JSON.stringify(obj), {headers: this.headers})
      .toPromise()
      .then(response => {
          try {
            let result = response;
            switch (result.code) {
              case '200':
                return result.data;
              case '-1':
                throw new Error(result.message);
            }
          }
          catch (error) {
            this.handleError(error);
          }

        }
      )
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    return Promise.reject(error.message || error);
  }
}


// WEBPACK FOOTER //
// ./src/app/service/turboper-history.service.ts
